import store from '../store/globalStore'

// 调试状态
const IS_DEBUG = true

const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

// request
const resquestUtil = option => {
    const baseUrl = store.getters['settings/baseUrl']
    return uni.request({
        url: baseUrl + option.url,
        data: option.data,
        method: option.method,
        success: option.success,
        fail: option.fail,
    })
}

const wechatLogin = success => {
    // 登录
    uni.login({
        success: res => {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            if (!res.code) {
                uni.showToast({
                    title: '未取得用户code',
                    icon: 'none',
                    duration: 1000,
                })
                return
            }
            success(res.code)
        },
    })
}

// console log
const showConsoleLogs = option => {
    if (IS_DEBUG) {
        console.log(option.type)
        console.log(option.result)
    }
}

// wx show toast
const showToast = (tips, timer, type) => {
    if (!timer || typeof timer === 'string' || timer > 5000 || timer < 1500) {
        timer = 2000
    }
    uni.showToast({
        title: tips,
        icon: type || 'none',
        duration: timer,
    })
}

function showLoading(title = '加载中') {
    uni.showLoading({ title })
}

function hideLoading() {
    uni.hideLoading()
}

function navigateTo(path, options) {
    const { query, ...params } = options || {}
    let url = path
    if (query) {
        const p = Object.entries(query)
            .map(i => i.join('='))
            .join('&')
        if (url.indexOf('?') > -1) {
            url = url + '&' + p
        } else {
            url = url + '?' + p
        }
    }
    uni.navigateTo({
        url,
        fail(e) {
            console.log(e)
        },
        ...params,
    })
}

function preloadPage(path) {
    return new Promise((resolve, reject) => {
        uni.preloadPage({
            url: path,
            complete: resolve,
            fail: reject,
        })
    })
}

// 验证车牌号或则订单号
export const carNo = 'CAR_NO'
export const deviceNo = 'WAYBILL_NO'

function judgeType(code) {
    let CarNoRegRex = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}/
    if (CarNoRegRex.test(code)) {
        return 'CAR_NO'
    } else {
        return 'WAYBILL_NO'
    }
}

function formatTimeStr(time) {
    const date = new Date(time)
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()

    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    const t1 = [year, month, day].map(formatNumber).join('-')
    const t2 = [hour, minute, second].map(formatNumber).join(':')

    return `${t1} ${t2}`
}

function printLaunchOptionsSync() {
    var path = uni.getLaunchOptionsSync().path
    console.log(path)
}

function isValidPhone(phoneNumber) {
    return /^1[3456789]\d{9}$/.test(phoneNumber)
}

function calculateDistance(first, second) {
    var rad1 = (first.lat * Math.PI) / 180.0
    var rad2 = (second.lat * Math.PI) / 180.0
    var theta = rad1 - rad2
    var radtheta = (first.lng * Math.PI) / 180.0 - (second.lng * Math.PI) / 180.0

    var r = 6378137
    return (
        r *
        2 *
        Math.asin(
            Math.sqrt(
                Math.pow(Math.sin(theta / 2), 2) +
                    Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(radtheta / 2), 2),
            ),
        )
    )
}

function getDateText(date) {
    return date.format('YYYYMMDD')
}

function getDateRangeText(start, end) {
    return start.format('YYYYMMDD') + '-' + end.format('YYYYMMDD')
}

function showErrorMessage(message) {
    uni.showToast({
        title: message,
        image: '../../static/fail.png',
    })
}

function showSuccessMessage(message) {
    uni.showToast({
        title: message,
        image: '../../static/success.png',
    })
}

function redirectTo(pagePath) {
    uni.redirectTo({
        url: pagePath,
        fail(e) {
            console.log('Redirect to page error:', e)
        },
    })
}

function switchTab(tab) {
    uni.switchTab({
        url: tab,
    })
}

function navigateBack() {
    uni.navigateBack()
}

function reLaunch(path) {
    uni.reLaunch({
        url: path,
    })
}

function showUserLoginDialog() {
    uni.showModal({
        title: '提示',
        confirmText: '去登录',
        content: '该功能需要登录才可以访问，是否登录？',
        success: res => {
            if (res.confirm) {
                // redirectTo('/pages/login/main')
            } else {
                console.log('User choose not to login')
            }
        },
    })
}

function setNavigationBarTitle(title) {
    uni.setNavigationBarTitle({
        title,
    })
}

function wxUploadFile(url, params) {
    const Authorization = store.getters['settings/token']
    const baseUrl = store.getters['settings/baseUrl']
    const { success, fail, complete, header, files, ...query } = params
    const headers = Object.assign({}, header)
    if (Authorization) {
        Object.assign(headers, { Authorization })
    }
    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: baseUrl + url,
            complete,
            header: headers,
            ...query,
            success(res) {
                const result = JSON.parse(res.data)
                success && success(result)
                resolve(result)
            },
            fail(err) {
                fail && fail(err)
                reject(err)
            },
        })
    })
}

function uploadFile(url, params = {}) {
    const { files, ...query } = params
    if (files && files.length > 0) {
        return new Promise((resolve, reject) => {
            Promise.all(
                files.map(i => {
                    const data = Object.assign({}, query, { filePath: i })
                    return wxUploadFile(url, data)
                }),
            )
                .then(list => {
                    const allPhoto = []
                    list.forEach(res => {
                        if (res.success) {
                            allPhoto.push(res.data)
                        }
                    })
                    resolve(allPhoto)
                })
                .catch(reject)
        })
    }
    return wxUploadFile(url, query)
}

const formatDate = () => {
    const date = new Date()
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    let curDate = year + '-' + month + '-' + day
    return curDate
}

function previewImage(urls = [], current = 0) {
    uni.previewImage({
        urls,
        current,
        indicator: 'none',
        loop: false,
        success: ({ index, tapIndex }) => {
            // console.log(index)
        },
        fail: e => {
            console.log('uni.previewImage: ', e)
        },
    })
}

function checkCertStatus(time) {
    time = time.replace(/\-/g, '/')
    return new Date(time).getTime() + 8.64e7 - Date.now() >= 0 ? '正常' : '过期'
}

// 检测是否为微信上传图片
function checkIsWecharFile(url = '') {
    return url && /^(https?|wxfile)\:\/\/tmp/.test(url)
}

module.exports = {
    formatTime,
    showConsoleLogs,
    showToast,
    wechatLogin,
    resquestUtil,
    showLoading,
    hideLoading,
    navigateTo,
    preloadPage,
    formatNumber,
    formatTimeStr,
    printLaunchOptionsSync,
    isValidPhone,
    calculateDistance,
    getDateText,
    getDateRangeText,
    showErrorMessage,
    showSuccessMessage,
    judgeType,
    redirectTo,
    switchTab,
    navigateBack,
    reLaunch,
    showUserLoginDialog,
    setNavigationBarTitle,
    uploadFile,
    formatDate,
    previewImage,
    checkCertStatus,
    checkIsWecharFile,
}
